<template>
  <el-container :style="{height: formStyle}">
    <el-header>
      <div style="">
        <div style="display: inline-block">
          <el-button icon="el-icon-back" size="small" style="font-family: Microsoft YaHei" type="text"
                     @click="goBack">返回
          </el-button>
        </div>
        <div style="display: inline-block">|</div>
        <div style="display: inline-block;">
          <div style="padding-bottom: 15px;margin-left:10px">
            <span style="font-family: Microsoft YaHei;display: inline-block; font-size: 14px;">编辑增值元数据</span>
          </div>
        </div>
        <div style="border-bottom: solid 1px #C9C9C9;"></div>
      </div>
    </el-header>
    <el-main style="padding: 0px">
      <div style="font-family: PingFangSC-Regular">
        <el-form ref="formData" :model="formData" :rules="rules" class="demo-ruleForm">
          <el-form-item :label-width='itemWidth' label="图书名称：" prop="bookName">
            <el-input v-model="formData.bookName" :style="inputWidth" autocomplete="off" required="true"></el-input>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="选题号：" prop="topicNumber">
            <el-input v-model="formData.topicNumber" :style="inputWidth" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="ISBN：" prop="isbn">
            <el-input v-model="formData.isbn" :style="inputWidth" autocomplete="off"
                      v-bind:disabled="bookType === 1"></el-input>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="主   编：">
            <el-input v-model="formData.mainEditor" :style="inputWidth" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="副 主 编：">
            <el-input v-model="formData.deputyEditor" :style="inputWidth" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="封  面：">
            <img v-if="UTIL.isNotEmpty(formData.indexImg)" :src="formData.indexImg" height="200px" width="400px"/>
            <el-upload ref="upload" :action="uploadFilePath"
                       :limit=1
                       :on-success="uploadImgSuccess"
                       :show-file-list=false>
              <el-button size="small" style="width: 180px;" type="primary">上传图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="图书简介：">
            <el-input v-model="formData.summary" :style="inputWidth" autocomplete="off" type="textarea"></el-input>
          </el-form-item>
          <el-form-item :label-width='itemWidth' label="图书分类：">
            <el-cascader v-model="formData.category" :options="bookSubTagList"
                         :props="{label: 'name', value: 'id', checkStrictly: true}" clearable filterable
                         style="width: 100%;"/>
          </el-form-item>
          <el-form-item v-if="pageType === 'book' && bookType === 1" :label-width='itemWidth' label="是否显示电子书：">
            <el-radio-group v-model="formData.hidden">
              <span><el-radio :label="0">显示</el-radio></span>
              <span style="margin-left:20px;"><el-radio :label="1">隐藏</el-radio></span>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="pageType !== 'book'" :label-width='itemWidth' label="资源开放类型：">
            <el-radio-group v-model="formData.sourcePubType">
              <div>
                <el-radio :label="1">加密（读者通过扫图书贴码并激活后才可查看资源，图书增值服务由人卫智数提供）</el-radio>
              </div>
              <div style="margin-top:10px;">
                <el-radio :label="2">开放（读者微信扫码即可查看资源，无权限要求）</el-radio>
              </div>
              <div style="margin-top:10px;">
                <el-radio :label="3">会员（读者通过微信扫码并且是人卫助手会员才可以查看资源）</el-radio>
              </div>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
    <el-footer>
      <div style="text-align: left">
        <el-button size="small" type="success" @click="confirm">确定</el-button>
      </div>
    </el-footer>
  </el-container>
</template>

<script>
export default {
  name: "EditIncreaseMetadata",
  data() {
    let checkTopicNumber = (rule, value, callback) => {
      if (UTIL.isEmpty(value)) {
        return callback(new Error('请输入选题号'));
      }
      let reg = /^[1-2][0-9]{9}$/;
      if (!reg.test(value)) {
        return callback(new Error('由10位数字组成，必须以数字1或者2开头'));
      }
      callback();
    };
    let checkIsbn = (rule, value, callback) => {
      if (UTIL.isNotEmpty(value) && value.indexOf('-') === -1) {
        return callback(new Error('ISBN号必须包含-'));
      }
      callback();
    };
    return {
      formData: {},
      itemWidth: '160px',
      uploadFilePath: CONST.SERVICE_REST_PACKAGE + 'increaseBook/uploadFile',
      uploadImg: CONST.SERVICE_REST_PACKAGE + 'increaseBook/uploadImg',
      inputWidth: 'width:400px;',
      pageType: '',
      formStyle: '',
      bookSubTagList: [],
      bookType: '',
      rules: {
        bookName: [
          {required: true, message: '请输入图书名称', trigger: 'blur'}
        ],
        topicNumber: [
          {required: true, validator: checkTopicNumber, trigger: 'blur'}
        ],
        isbn: [
          {validator: checkIsbn, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    goBack: function () {
      if (this.pageType === 'book') {
        this.$router.push("/bookLib")
      } else {
        this.$router.push("/increaseBook/bookList");
      }
    },
    handleRemove(file, fileList) {
      if (file && file.status === "success") {
        return this.$confirm('确认删除此图片？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.formData.indexImg = '';
        }).catch(() => {
          reject(false);
        });
      }
    },
    uploadImgSuccess(response, file, fileList) {
      this.formData.indexImg = CONST.YMER_SERVICE_REST_PACKAGE + response.path.substring(1);
      this.$refs.upload.clearFiles();
    },
    confirm() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.bookId = this.$route.params.id
          this.axios.post('/pmph/action/book/updateIncreaseMetadata', this.formData)
            .then(() => {
              if (this.pageType === 'book') {
                this.$router.push("/bookLib")
              } else {
                this.$router.push("/increaseBook/bookList");
              }
            })
        } else {
          return false;
        }
      });
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.axios.get('/pmph/action/book/selectCategoryAndSummaryAndByIsbn', {
            params: {
              isbn: this.formData.isbn,
              bookType: this.bookType
            }
          }).then(async (response) => {
            this.formData.category = response.data.category
            this.formData.summary = response.data.summary
            if (this.formData.category.length === 0) {
              await UTIL.sleep(1000)
              this.$message.warning("未查询到分类信息")
            }
            if (UTIL.isEmpty(this.formData.summary)) {
              await UTIL.sleep(1000)
              this.$message.warning("未查询到图书简介")
            }
            if (UTIL.isEmpty(response.data.bPrice)) {
              await UTIL.sleep(1000)
              this.$message.warning("未更新纸书价格")
            } else {
              await UTIL.sleep(1000)
              this.$message.warning("更新后纸书价格为" + response.data.bPrice)
            }
          })
        } else {
          return false;
        }
      });
    },
    handleUploadSuccess(response) {
      this.$emit("upload", this.fieldIndex, response.path)
    },
    handleUploadError(err, file, fileList) {
      this.$message.error("图片上传失败")
    }
  },
  created() {
    this.formStyle = CONST.WORKSPACE_HEIGHT - 40 + 'px'
    this.formData = this.$route.params.formData
    this.pageType = this.$route.params.pageType
    this.bookType = this.$route.params.bookType
    this.axios.get('/pmph/action/tag/selectBookSubTagTree').then((response) => {
      this.bookSubTagList = response.data
    })
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 16px;
}

.el-upload-list__item {
  transition: none !important;
}

.upload-template {
  display: inline-block;
}
</style>
